package com.dlc.yunguang.activitynew;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.dlc.commonlibrary.ble.RfidHelper;
import com.dlc.commonlibrary.dialog.SureDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.commonlibrary.widget.popup.CommonPopupList;
import com.dlc.yunguang.adapter.LaundryAdapter;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.net.bean.BackBean;
import com.dlc.yunguang.net.bean.OfficeBean;
import com.dlc.yunguang.net.bean.OrderGetBean;
import com.dlc.yunguang.net.bean.RFIDSpecListBean;
import com.dlc.yunguang.net.exception.ErrorMsgException;
import com.dlc.yunguang.net.protocol.StockProto;
import com.dlc.yunguang.net.protocol.base.HttpProtocol;
import com.dlc.yunguang.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/19 0019.
 */

public class DistributeActivity extends BaseActivity {

    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.order_number)
    TextView mOrderNumber;
    @BindView(R.id.hotel)
    TextView mHotel;
    @BindView(R.id.pro_name)
    TextView mProName;
    @BindView(R.id.classify)
    TextView mClassify;
    @BindView(R.id.pro_count)
    TextView mProCount;
    @BindView(R.id.check)
    Button mCheck;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_hotel)
    TextView mTvHotel;
    @BindView(R.id.drop_hotel)
    FrameLayout mDropHotel;
    @BindView(R.id.item_hotel)
    CommonItemView mItemHotel;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.drop_order)
    FrameLayout dropOrder;
    @BindView(R.id.item_order)
    CommonItemView itemOrder;

    private LaundryAdapter mLaundryAdapter;
    private ArrayList<String> rfids = new ArrayList<>();
    private CommonPopupList mHotelPopup;//酒店
    List<OfficeBean.DataBean> HotelList = new ArrayList<>();
    private String HotelId = null;

    private CommonPopupList mOrderPopup;//回收单
    List<OrderGetBean.DataBean.ListBean> OrderList = new ArrayList<>();
    private String OrderId = null;
    private List<String> officeList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleBar.leftImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.titleText.setText("科室分发");
        rfids = getIntent().getStringArrayListExtra("rfids");

        // 查询送货单详情
        queryOrderDetail();

        initRecyclerView();
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_distribute;
    }

    private void initRecyclerView() {
        mLaundryAdapter = new LaundryAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mLaundryAdapter);
        mHotelPopup = CommonPopupList.newBuilder(getActivity())
                .setWidthEquals(mDropHotel)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        // TODO: 2017/7/20
                        mTvHotel.setText(item);
                        if (HotelList != null) {
                            HotelId = HotelList.get(position).id;
                            getOrderData(HotelId);
                        }
                    }
                })
                .build();

        mOrderPopup = CommonPopupList.newBuilder(getActivity())
                .setWidthEquals(dropOrder)
                .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                    @Override
                    public void onSelectItem(CommonPopupList popup, String item, int position) {
                        popup.dismiss();
                        // TODO: 2017/7/20
                        tvOrder.setText(item);
                        if (OrderList != null) {
                            OrderId = OrderList.get(position).id;
                        }
                    }
                })
                .build();

    }



    /**
     * 查询订单详情
     */
    private void queryOrderDetail() {
        String rfid = "";
        for (int i = 0; i < rfids.size(); i++) {
            rfid = rfid + rfids.get(i) + ",";
        }
        if (!TextUtils.isEmpty(rfid)) {
            rfid = rfid.substring(0, rfid.length() - 1);
        } else {
            rfid = "-1";
        }
        mOrderNumber.setText(String.valueOf(rfids.size()));
        StockProto.get()
                .rfid_spec(rfid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RFIDSpecListBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        showOneToast(e.getMessage());
                    }

                    @Override
                    public void onNext(RFIDSpecListBean dataBean) {
                        mLaundryAdapter.setNewData(dataBean.data);
                        for (RFIDSpecListBean.DataBean bean : dataBean.data) {
                            if (!TextUtils.isEmpty(bean.office)) {
                                officeList.add(bean.office);
                            }
                        }
                        officeList = RfidHelper.removeDuplicateWithOrder(officeList);
                        getPopupListData();
                    }
                });
    }

    private void commitData() {
        String rfid = "";
        for (int i = 0; i < rfids.size(); i++) {
            rfid = rfid + rfids.get(i) + ",";
        }
        if (!TextUtils.isEmpty(rfid)) {
            rfid = rfid.substring(0, rfid.length() - 1);
        } else {
            rfid = "-1";
        }
        rfid_divide_new(rfid, HotelId, OrderId, "");
    }

    private void rfid_divide_new(final String rfid, String office, String wash_id, String confirm) {

        if (TextUtils.isEmpty(office)){
            showOneToast("科室不能为空");
            return;
        }
        if (TextUtils.isEmpty(wash_id)){
            showOneToast("回收单号不能为空");
            return;
        }
        showWaitingDialog("请等待", false);
        StockProto.get().rfid_divide_new(rfid, office, wash_id, confirm, new HttpProtocol.Callback<BackBean>() {
            @Override
            public void onSuccess(BackBean backBean) {
                dismissWaitingDialog();
                showOneToast(backBean.msg);
                //getDetailData(backBean.data.order_id + "");
            }

            @Override
            public void onFailed(int code, ErrorMsgException e) {
                showOneToast(e.getMessage());
                dismissWaitingDialog();
                if (code == -101) {
                    SureDialog sureDialog =
                            new SureDialog(DistributeActivity.this, "提示有其他科室布草，是否确定生成送洗单，选“确定”，可以生成送洗单。");
                    sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                        @Override
                        public void sure() {
                            rfid_divide_new(rfid, HotelId, OrderId, "1");
                        }

                        @Override
                        public void cancle() {
                            finish();
                        }
                    });
                }
            }
        });
    }


    @OnClick({R.id.check, R.id.drop_hotel,R.id.drop_order})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check:
                if (TextUtils.isEmpty(HotelId)) {
                    showOneToast("请选择科室");
                    return;
                }
                SureDialog sureDialog = new SureDialog(DistributeActivity.this, "全部读取完成，确认提交");
                sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                    @Override
                    public void sure() {
                        commitData();
                    }

                    @Override
                    public void cancle() {

                    }
                });
                break;
            case R.id.drop_hotel:
                mHotelPopup.showAsDropDown(view);
                break;
            case R.id.drop_order:
                mOrderPopup.showAsDropDown(view);
                break;
        }
    }
    private void getPopupListData() {
        StockProto.get().getOfficenew2().
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Observer<OfficeBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        LogPlus.e(e.getMessage());
                    }

                    @Override
                    public void onNext(OfficeBean hotelBean) {
                        if (hotelBean != null && hotelBean.data != null) {
                            List<String> datas = new ArrayList<>();

                            Iterator<OfficeBean.DataBean> it = hotelBean.data.iterator();
                            //while(it.hasNext()){
                            //    String str = it.next().title;
//                            for (int j = 0; j < hotelBean.data.size(); j++) {
//                                for (int i = 0; i < officeList.size(); i++) {
//                                    if (officeList.get(i).equals(hotelBean.data.get(j).title)) {
//                                        HotelList.add(hotelBean.data.get(j));
//                                    }
//                                }
//                            }
                            // }
                            HotelList = hotelBean.data;
                            for (int i = 0; i < HotelList.size(); i++) {
                                datas.add(HotelList.get(i).title);
                            }

                            mHotelPopup.setData(datas);
                        }
                    }
                });
    }
    private void getOrderData(String office_id) {
        OrderList.clear();
        StockProto.get().rfid_wash(office_id,"1", new HttpProtocol.Callback<OrderGetBean>() {
            @Override
            public void onSuccess(OrderGetBean hotelBean) {
                if (hotelBean != null && hotelBean.data != null) {
                    List<String> datas = new ArrayList<>();
                    OrderList = hotelBean.data.list;
                    for (int i = 0; i < hotelBean.data.list.size(); i++) {
                        datas.add( hotelBean.data.list.get(i).orderno);
                    }

                    mOrderPopup.setData(datas);
                }
            }

            @Override
            public void onFailed(int code, ErrorMsgException e) {

            }
        });


    }
}
